import csv
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'travel_recommend.settings')
django.setup()
from travel.models import City, Travel, Comments
from travel.serializers import TravelModelSerializer


def city_to_sql():
    with open('city.csv', 'r', encoding='utf8') as f:
        read = csv.reader(f)
        next(read)
        for city in read:
            name = city[0]
            print(name)
            City.objects.create(name=name)


def province_to_sql():
    province_list = ['北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏',
                     '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东',
                     '广西', '海南', '重庆', '四川', '贵州', '云南', '西藏', '陕西', '甘肃',
                     '青海', '宁夏', '新疆', '台湾', '香港', '澳门']
    for province in province_list:
        print(province)
        City.objects.create(name=province)


def travel_to_sql():
    with open('travel.csv', 'r', encoding='utf8') as f:
        read = csv.reader(f)
        next(read)
        for travel in read:
            print(travel[0])
            cities = City.objects.filter(name=travel[2])

            Travel.objects.create(
                name=travel[0],
                city_id=cities[0].id,
                price=float(travel[1]),
                star=travel[3],
                address=travel[4],
                detail_url=travel[5],
                comment_total=int(travel[6]),
                detail_intro=travel[7],
                short_intro=travel[8],
                img_list=travel[9],
                cover=travel[10],
                sale_count=travel[11],
                districts=travel[12],
                score=travel[13]
            )


def comments_to_sql():
    with open('comments.csv', 'r', encoding='utf8') as f:
        read = csv.reader(f)
        next(read)
        for comment in read:
            travel = Travel.objects.filter(name=comment[0])
            travel = TravelModelSerializer(travel, many=True).data
            try:
                Comments.objects.create(
                    content=comment[1],
                    date=comment[2],
                    travel_id=travel[0]['id']
                )
                print(travel[0]['name'])
            except:
                continue


if __name__ == '__main__':
    # city_to_sql()
    # travel_to_sql()
    # comments_to_sql()
    # pass

    # province_to_sql()
    # travel_to_sql()
    comments_to_sql()
    pass